import {
  formatSeconds,
} from '../../../utils/util.js'

let app = getApp()
Page({
  data: {
    spinShow: false,
    paperId: null,
    paper: {},
    answer: {},
    timer: null,
    doTime: 0,
    remainTime: 0,
    remainTimeStr: '',
    modalShow: false,
    result: 0,
    timeOutShow: false,
    // 新增：单题模式相关数据
    currentQuestionIndex: 0,
    currentQuestion: {}, // 当前题目对象
    allQuestions: [],
    answerSheetVisible: false, // 答题详情显示状态
    
    // 新增：当前题目的计算结果
    currentUserAnswer: '',
    currentCorrectAnswer: '',
    currentQuestionResult: '',
    currentAnswerScore: 0
  },

  onLoad: function(options) {
    let paperId = options.id
    let _this = this
    _this.setData({
      spinShow: true
    });
    app.formPost('/api/wx/student/exampaper/answer/read/' + paperId, null)
      .then(res => {
        _this.setData({
          spinShow: false
        });
        if (res.code === 1) {
          console.log('试卷数据:', res.response);
          
          // 重新组织数据，将题目和答案关联起来
          const allQuestions = this.organizeQuestionsWithAnswers(res.response);
          
          _this.setData({
            paper: res.response.paper,
            answer: res.response.answer,
            paperId: paperId,
            allQuestions: allQuestions
          });
          
          // 设置第一题并计算显示数据
          _this.setCurrentQuestion(0);
        }
      }).catch(e => {
        _this.setData({
          spinShow: false
        });
        app.message(e, 'error')
      })
  },

  // 重新组织数据，将题目和答案关联起来
  organizeQuestionsWithAnswers: function(response) {
    const { paper, answer } = response;
    const allQuestions = [];
    
    console.log('开始组织数据...');
    console.log('题目数量:', paper.titleItems[0].questionItems.length);
    console.log('答案数量:', answer.answerItems.length);
    
    // 提取所有题目
    (paper.titleItems || []).forEach(titleItem => {
      (titleItem.questionItems || []).forEach(question => {
        // 找到对应的答案项
        const answerItem = (answer.answerItems || []).find(item => 
          item.questionId === question.id
        );
        
        // 计算题目状态
        let displayStatus = 'unanswered';
        if (answerItem) {
          // 检查是否是未作答（content 为 "X"）
          if (answerItem.content === 'X') {
            displayStatus = 'unanswered';
          } else if (answerItem.doRight === true) {
            displayStatus = 'correct';
          } else if (answerItem.doRight === false) {
            displayStatus = 'wrong';
          } else if (answerItem.doRight === null) {
            displayStatus = 'pending';
          }
        }
        
        const questionWithAnswer = {
          ...question,
          titleName: titleItem.name,
          answerItem: answerItem || null,
          displayStatus: displayStatus // 预计算的状态
        };
        
        console.log(`题目 ${question.itemOrder} 状态:`, {
          题目ID: question.id,
          用户答案: answerItem ? answerItem.content : '无',
          是否正确: answerItem ? answerItem.doRight : '无',
          状态: displayStatus
        });
        
        allQuestions.push(questionWithAnswer);
      });
    });
    
    // 按 itemOrder 排序
    return allQuestions.sort((a, b) => a.itemOrder - b.itemOrder);
  },

  // 设置当前题目并计算显示数据
  setCurrentQuestion: function(index) {
    if (index < 0 || index >= this.data.allQuestions.length) {
      return;
    }
    
    const question = this.data.allQuestions[index];
    this.setData({
      currentQuestionIndex: index,
      currentQuestion: question
    });
    
    // 计算并设置显示数据
    this.calculateDisplayData(question);
  },

  // 计算显示数据
  calculateDisplayData: function(question) {
    if (!question) return;
    
    const userAnswer = this.getUserAnswer(question);
    const correctAnswer = this.getCorrectAnswer(question);
    const result = this.getQuestionResult(question);
    const score = this.getAnswerScore(question);
    
    console.log('计算显示数据:', {
      题目: question.itemOrder,
      用户答案: userAnswer,
      正确答案: correctAnswer,
      结果: result,
      得分: score
    });
    
    this.setData({
      currentUserAnswer: userAnswer,
      currentCorrectAnswer: correctAnswer,
      currentQuestionResult: result,
      currentAnswerScore: score
    });
  },

  // 获取用户答案
  getUserAnswer: function(question) {
    if (!question || !question.answerItem || !question.answerItem.content) {
      return '未作答';
    }
    
    // 如果答案是'X'，视为未作答
    if (question.answerItem.content === 'X') {
      return '未作答';
    }
    
    return question.answerItem.content;
  },

  // 获取正确答案
  getCorrectAnswer: function(question) {
    if (!question) return '';
    
    if (question.questionType === 1 || question.questionType === 2 || question.questionType === 5) {
      return question.correct || '';
    } else if (question.questionType === 3) {
      // 判断题处理
      return question.correct === 'A' ? '正确' : '错误';
    } else if (question.questionType === 4) {
      return question.correctArray || '';
    }
    return '';
  },

  // 获取题目结果
  getQuestionResult: function(question) {
    if (!question || !question.answerItem) {
      return 'unanswered';
    }
    
    const answerItem = question.answerItem;
    
    // 检查是否是未作答（content 为 "X"）
    if (answerItem.content === 'X') {
      return 'unanswered';
    }
    
    if (answerItem.doRight === true) {
      return 'correct';
    } else if (answerItem.doRight === false) {
      return 'wrong';
    } else if (answerItem.doRight === null) {
      return 'pending';
    }
    
    return 'unanswered';
  },

  // 获取答案得分
  getAnswerScore: function(question) {
    if (!question || !question.answerItem) {
      return 0;
    }
    return question.answerItem.score || 0;
  },

  onUnload() {
    clearInterval(this.data.timer)
  },

  returnRecord() {
    wx.reLaunch({
      url: '/pages/record/index',
    });
  },

  timeOut() {
    clearInterval(this.data.timer)
    this.setData({
      timeOutShow: true
    });
  },

  // 上一题
  prevQuestion: function() {
    if (this.data.currentQuestionIndex > 0) {
      const newIndex = this.data.currentQuestionIndex - 1;
      this.setCurrentQuestion(newIndex);
    }
  },

  // 下一题
  nextQuestion: function() {
    const { currentQuestionIndex, allQuestions } = this.data;
    if (currentQuestionIndex < allQuestions.length - 1) {
      const newIndex = currentQuestionIndex + 1;
      this.setCurrentQuestion(newIndex);
    }
  },

  // 显示/隐藏答题详情
  toggleAnswerSheet: function() {
    const newState = !this.data.answerSheetVisible;
    console.log('切换答题详情:', newState);
    
    if (newState) {
      // 当打开答题详情时，检查所有题目的状态
      console.log('答题详情打开，检查所有题目状态:');
      this.data.allQuestions.forEach((question, index) => {
        console.log(`题目 ${index + 1}:`, {
          题号: question.itemOrder,
          用户答案: question.answerItem ? question.answerItem.content : '无',
          是否正确: question.answerItem ? question.answerItem.doRight : '无',
          状态: question.displayStatus
        });
      });
    }
    
    this.setData({
      answerSheetVisible: newState
    });
  },

  // 跳转到指定题目
  jumpToQuestion: function(e) {
    const index = e.currentTarget.dataset.index;
    console.log('跳转到题目:', index);
    
    const question = this.data.allQuestions[index];
    console.log('目标题目状态:', question.displayStatus);
    
    this.setCurrentQuestion(index);
    this.setData({
      answerSheetVisible: false
    });
  },

  // 判断选项是否被用户选择
  isUserAnswer: function(question, option) {
    const userAnswer = this.getUserAnswer(question);
    return userAnswer === option.prefix;
  },

  // 判断选项是否是正确答案
  isCorrectOption: function(question, option) {
    if (!question || !question.correct) return false;
    return question.correct === option.prefix;
  },

  // 获取选项状态类名
  getOptionStatus: function(question, option) {
    const isUserAnswer = this.isUserAnswer(question, option);
    const isCorrect = this.isCorrectOption(question, option);
    
    if (isUserAnswer && isCorrect) {
      return 'correct-answer';
    } else if (isUserAnswer && !isCorrect) {
      return 'wrong-answer';
    } else if (isCorrect) {
      return 'correct-option';
    }
    return '';
  }
});